//
//  LocalizableManager.swift
//  AMICTR
//
//  Created by QFX on 2023/12/25.
//

import UIKit
enum LanguageType {
    case chinese,english,jp,auto
}
class LocalizableManager: NSObject {
    static func localValue(_ str:String) -> String {
        LocalizableManager.shared.localValue(str: str)
    }
    static func setLanguage(_ type:LanguageType){
        LocalizableManager.shared.setLanguage(type)
    }
    //单例
    static let shared = LocalizableManager()
     private override init() {      }
    var bundle:Bundle = Bundle.main
    private func localValue(str:String) -> String{
        //table参数值传nil也是能够的，传nil体系就会默许为Localizable
        bundle.localizedString(forKey: str, value: nil, table: "Localizable")
    }
    /// 获取体系言语办法-->能够依据本身事务场景进行处理
    private func getCurrentLanguage() -> String {
        let preferredLang = NSLocale.preferredLanguages.first! as NSString
        switch String(describing: preferredLang) {
        case "en-US", "en-CN":
            return "en"//英文
        case "zh-Hans-US","zh-Hans-CN","zh-Hant-CN","zh-TW","zh-HK","zh-Hans":
            return "cn"//中文
        default:
            return "en"
        }
    }
    private func setLanguage(_ type:LanguageType){
        var typeStr = ""
        switch type {
        case .chinese:
            typeStr = "zh-Hans"
            UserDefaults.standard.setValue("zh-Hans", forKey: "language")
        case .english:
            typeStr = "en"
            UserDefaults.standard.setValue("en", forKey: "language")
        case .jp:
            typeStr = "jp"
            UserDefaults.standard.setValue("jp", forKey: "language")
        default:
            break
        }
        //回来项目中 en.lproj 文件的途径
        let path = Bundle.main.path(forResource: typeStr, ofType: "lproj")
        //用这个途径生成新的bundle
        bundle = Bundle(path: path!)!
        if type == .auto {
            //和体系言语共同
            bundle = Bundle.main
            UserDefaults.standard.removeObject(forKey: "language")
        }
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "languageChanged"), object: nil)
    }
}
